package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private HttpServletRequest request;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void add(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        // 拷贝属性
        BeanUtils.copyProperties(employeeDTO, employee);
        // 添加创建时间修改时间,启用状态,创建人,修改人
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        employee.setStatus(StatusConstant.ENABLE);
        /*
         从请求头令牌中获取id值第一种方法:

        // 从请求头令牌中 获取修改人id
            // 1. 需要使用获取请求头对象,注入HttpServletRequest
            // 2. 从请求头中获取令牌
            // 3.解析令牌
            // 4.获取id
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT("itcast", token);
        Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
*/
        /*
         从请求头令牌中获id值第二种方法:
            通过线程本地储存获取id
          - public void set(T value) 	设置当前线程的线程局部变量的值
          - public T get() 		        返回当前线程所对应的线程局部变量的值
          - public void remove()        移除当前线程的线程局部变量

       */
        //Long empId = BaseContext.getCurrentId();
        // 修改人
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        // 设置密码
        // 给密码加密
        byte[] password = PasswordConstant.DEFAULT_PASSWORD.getBytes();
        employee.setPassword(DigestUtils.md5DigestAsHex(password));
        // 调用mapper层
        employeeMapper.add(employee);
    }

    /**
     * 员工分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO dto) {
        // 调用mapper层
        Page<Employee> employees = employeeMapper.pageQuery(dto);
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        long total = employees.getTotal();
        List<Employee> result = employees.getResult();
        return new PageResult(total, result);


    }

    /**
     * 员工账号状态更新
     *
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        // 调用mapper层
        // 第一种写法:
        employeeMapper.updateStatus(status, id);
        // 第二种写法:
        // 1.先构造出一个员工对象,然后把参数传入
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        // 2.调用mapper方法把员工对象传入
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public EmployeeDTO findById(Long id) {
        // 调用mapper层
        EmployeeDTO employeeDTO = new EmployeeDTO();
        Employee employee = employeeMapper.findById(id);
        BeanUtils.copyProperties(employee, employeeDTO);
        return employeeDTO;
    }

    /**
     * 更新员工信息
     *
     * @param employeeDTO
     */
    @Override

    public void update(EmployeeDTO employeeDTO) {
        // 调用mapper层,参数是Employee对象
        // 构造一个Employee对象,把EmployeeDTO参数对象拷贝过去
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    /**
     * 更新密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        // 根据id获取数据库中数据
        Long empId = BaseContext.getCurrentId();

        Employee employee = employeeMapper.findById(empId);
        String oldPassword = passwordEditDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 验证密码
        if (!oldPassword.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED + MessageConstant.PASSWORD_ERROR);
        }
        String newPassword = passwordEditDTO.getNewPassword();

        employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));

        // 调用mapper层
        employeeMapper.update(employee);
    }


}

